<template>
  <div class="index-container  border-box">
    <a-space direction="vertical">
      <div style="background-color: #f0f2f5; padding: 20px;">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-card title="已用空间" :bordered="false">
              <a-progress
                type="circle"
                :width="80"
                :stroke-color="{
                  '0%': '#108ee9',
                  '100%': '#87d068'
                }"
                :percent="50"
              />
              <p>3/6GB</p>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card title="提示语" :bordered="false">
              <h1>您好</h1>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card title="回收站" :bordered="false">
              <a-space>
                <a-button type="primary" size="large" @click="openRecyclingBin">打开回收站</a-button>
                <a-popconfirm
                  title="确定要清空回收站吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="cleanRecyclingBin"
                >
                  <a-button type="danger" size="large" >清空回收站</a-button>
                </a-popconfirm>
              </a-space>
            </a-card>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-space>
          <a-button-group>
            <a-button type="primary" @click="uploadFile">上传</a-button>
          </a-button-group>
          <a-button-group>
            <a-button type="primary" @click="mkdir">新建文件夾</a-button>
            <a-button type="primary" @click="multiDown">下载</a-button>
            <a-button type="primary" @click="showCopyModal(selectedRows, true, true)">复制</a-button>
            <a-button type="primary" @click="showCopyModal(selectedRows, false, true)">移动</a-button>
            <a-button type="primary" @click="showShareModal(selectedRows)">分享</a-button>
            <a-popconfirm
              title="你确定要删除选中文件吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmDelete(selectedRows)"
            >
              <a-button type="danger">删除</a-button>
            </a-popconfirm>
          </a-button-group>
        </a-space>
      </div>
      <a-breadcrumb separator=">">
        <template v-for="item in dirInfo.path">
          <a-breadcrumb-item v-bind:key="item.id">
            <a v-if="dirInfo.id !== item.id" @click="getCurrentDirList(item.id)">{{ item.name }}</a>
            <a v-else>{{ item.name }}</a>
          </a-breadcrumb-item>
        </template>
      </a-breadcrumb>
      <standard-table
        :table-data="tableData"
        :table-head="tableHead"
        :row-selection="{ selectedRowKeys: selectedRowKeys, selectedRow: selectedRows, onChange: onSelectChange }"
        :pagination="false"
      >
        <div class="file-size" slot="name" slot-scope="{ record }">
          <a-icon type="file" theme="twoTone" />
          <span v-if="record.type !== 'dir'" @click="preview(record.id, record.type)" >{{ record.name }}.{{ record.type }}</span>
          <span v-else @click="getCurrentDirList(record.id)">{{ record.name }}</span>
        </div>
        <div slot="action" slot-scope="{ text, record }">
          <a-space>
            <a-button type="primary" size="small" @click="downloadOneFile(record)">
              下载
            </a-button>
            <a-button type="primary" size="small" @click="showShareModal(record)">
              分享
            </a-button>
            <a-button type="primary" size="small" @click="rename(record)">
              重命名
            </a-button>
            <a-button type="primary" size="small" @click="showCopyModal(record, true, false)">
              复制
            </a-button>
            <a-button type="primary" size="small" @click="showCopyModal(record, false, false)">
              移动
            </a-button>
            <a-popconfirm
              title="你确定要删除当前文件吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirmDelete(record)"
            >
              <a-button type="danger" size="small">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </div>
      </standard-table>
    </a-space>
    <!--    分享文件对话框-->
    <a-modal
      title="分享文件"
      :visible="shareModalVisible"
      cancelText="取消"
      okText="分享"
      @ok="confirmShare"
      @cancel="shareModalVisible = false"
    >
      <div class="file-size" style="text-align: center">
        <a-icon type="file" theme="twoTone" />
        <span v-if="shareItem.type !== 'dir'">{{ shareItem.name }}.{{ shareItem.type }}</span>
        <span v-else>{{ shareItem.name }}</span>
      </div>
      <a-form-model :model="shareForm" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ offset: 6 }">
        <a-form-model-item label="是否需要提取🐴">
          <a-switch v-model="shareForm.needCode" />
        </a-form-model-item>
        <a-form-model-item label="请输入提取🐴">
          <a-input :disabled="!shareForm.needCode" v-model="shareForm.shareCode"></a-input>
        </a-form-model-item>
        <a-form-model-item label="过期时间">
          <a-select v-model="shareForm.expiration" defaultValue="">
            <a-select-option value="">永久</a-select-option>
            <a-select-option value="1">一天</a-select-option>
            <a-select-option value="7">七天</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!--    分享码对话框-->
    <a-modal
      title="分享🐴"
      :visible="shareLinkModalVisible"
      @ok="shareLinkModalVisible = false"
      @cancel="shareLinkModalVisible = false"
    >
      <a-result title="分享成功">
        <template #icon>
          <a-icon type="smile" theme="twoTone" />
        </template>
        <template #extra>
          <div>
            <a-tag color="pink">
              分享链接
            </a-tag>
            <a-tag color="pink">
              {{ shareForm.shareLink }}
            </a-tag>
          </div>
          <div v-if="shareForm.shareCode">
            <a-tag color="pink">
              提取码
            </a-tag>
            <a-tag color="pink">
              {{ shareForm.shareCode }}
            </a-tag>
          </div>
        </template>
      </a-result>
    </a-modal>
    <!--    重命名对话框-->
    <a-modal title="重命名" :visible="renameModalVisible" @ok="confirmRename" @cancel="renameModalVisible = false">
      {{ renameForm }}
      <a-form-model>
        <a-form-model-item>
          <a-input v-model="renameForm.name"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!--    复制移动对话框-->
    <a-modal
      :title="isCopy ? '复制到' : '移动到'"
      :visible="copyModalVisible"
      @ok="confirmMoveAndCopy(isCopy, isMultiple)"
      @cancel="copyModalVisible = false"
    >
      <a-directory-tree :treeData="dirTreeDate" :replaceFields="replaceFields" @select="onSelect"> </a-directory-tree>
    </a-modal>
    <!--    新建文件夹对话框-->
    <a-modal title="新建文件夹" :visible="mkdirModalVisible" @ok="confirmMkdir" @cancel="mkdirModalVisible = false">
      <a-form-model :model="mkdirForm" layout="horizontal" :label-col="{ span: 4 }" :wrapper-col="{ offset: 4 }">
        <a-form-model-item label="文件夹名称">
          <a-input v-model="mkdirForm.dirName" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
      title="回收站"
      :visible="recycleBinVisible"
      width="700px"
      @ok="recycleBinVisible = false"
      @cancel="recycleBinVisible = false"
    >
      <standard-table :table-data="recycleBinTable" :table-head="recycleBinHead" :pagination="false">
        <div slot="name" slot-scope="{ record }" style="width: 400px">
          <a-icon type="file" theme="twoTone" />
          <span v-if="record.type !== 'dir'">{{ record.fileName }}.{{ record.fileType }}</span>
          <span v-else @click="getCurrentDirList(record.id)">{{ record.name }}</span>
        </div>
        <div slot="action" slot-scope="{ text, record }">
          <a-space>
            <a-button type="primary" @click="restoreFile(record)">恢复</a-button>
            <a-button type="danger" @click="removeCompletely(record)">彻底删除</a-button>
          </a-space>
        </div>
      </standard-table>
    </a-modal>
    <globalUploader></globalUploader>
  </div>
</template>

<script type="text/ecmascript-6">
import standardTable from '@/components/standardTable';
import globalUploader from '@/components/upload/GlobalUploader';
import { Base64 } from 'js-base64';
import Bus from '@/utils/bus';
export default {
  name: 'index',
  components: {
    standardTable,
    globalUploader
  },
  data() {
    return {
      tableHead: [
        {
          title: '文件名',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
          width: 500
        },
        {
          title: '文件大小',
          dataIndex: 'size'
        },
        {
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'action' }
        },
        {
          title: '最后修改时间',
          dataIndex: 'modifyTime',
          ellipsis: true
        }
      ],
      currentDirId: '',
      currentDirName: '',
      tableData: [],
      dirTreeDate: [],
      dirInfo: {},
      replaceFields: {
        children: 'children',
        title: 'name',
        slots: { type: 'root' },
        key: 'id'
      },
      shareModalVisible: false,
      shareItem: [],
      shareForm: {
        needCode: false,
        shareCode: '',
        expiration: ''
      },
      shareLinkModalVisible: false,
      renameModalVisible: false,
      renameForm: {
        id: '',
        type: '',
        name: ''
      },
      copyModalVisible: false,
      isCopy: false,
      isMultiple: false,
      mkdirModalVisible: false,
      mkdirForm: {
        userId: '',
        pid: '',
        dirName: ''
      },
      recycleBinVisible: false,
      recycleBinHead: [
        {
          title: '文件名',
          dataIndex: 'fileName',
          scopedSlots: { customRender: 'name' },
          width: 200
        },
        {
          title: '操作',
          dataIndex: 'id',
          scopedSlots: { customRender: 'action' }
        }
      ],
      recycleBinTable: [],
      selectedRowKeys: [],
      selectedRows: [],
      targetKey: '',
      copyItem: ''
    };
  },
  created() {
    this.getCurrentDirList();
  },
  provide() {
    return {
      getCurrentDirList: this.getCurrentDirList,
      downloadOneFile: this.downloadOneFile
    };
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        }
      };
    }
  },
  methods: {
    getDirTree() {
      console.log('获取目录树');
      const userId = this.$store.state.user.accountInfo.userId;
      this.$store
        .dispatch('dir/dirTree', { userId })
        .then(res => {
          console.log(res[1]);
          this.dirTreeDate = res;
        })
        .catch(reason => {
          console.log(reason);
        });
    },
    getCurrentDirList(pid) {
      console.log('获取当前目录下的文件和文件夹');
      const userId = this.$store.state.user.accountInfo.userId;
      this.$store
        .dispatch('dir/currentDirList', { userId, pid })
        .then(res => {
          this.dirInfo = res;
          this.dealDirAndFile(res.file, res.dirs);
          this.currentDirId = pid ? pid : 0;
          let name = res.path[res.path.length - 1].name;
          this.currentDirName = name;
          console.log('当前目录名称:', name);
          console.log(this.tableData);
        })
        .catch(reason => {
          console.log(reason);
        });
    },
    dealDirAndFile(files, dirs) {
      files.forEach(function(item) {
        dirs.push(item);
      });
      this.tableData = dirs;
    },
    showShareModal(shareItem) {
      this.shareModalVisible = true;
      this.shareItem = shareItem;
    },
    confirmShare() {
      let itemArray = [];
      itemArray.push(this.shareItem);
      const params = {
        item: itemArray,
        userId: this.$store.state.user.accountInfo.userId,
        shareLock: this.shareForm.needCode,
        shareCode: this.shareForm.shareCode,
        expirationTime: this.shareForm.expiration
      };
      this.$store
        .dispatch('share/shareFile', params)
        .then(res => {
          console.log('分享成功', res);
          this.shareModalVisible = false;
          this.shareLinkModalVisible = true;
          this.shareForm.shareCode = res.shareCode;
          this.shareForm.shareLink = window.location.href + 'share/' + res.shareLink;
        })
        .catch(reason => {
          console.log(reason);
        });
    },
    confirmDelete(deleteItem, isOne) {
      console.log('要删除的文件', deleteItem);
      const list = [];
      list.push(deleteItem);
      this.$store
        .dispatch('dir/deleteDir', list)
        .then(result => {
          this.getCurrentDirList(this.currentDirId);
          console.log('删除结果', result);
        })
        .catch(reason => {
          console.log('删除失败', reason);
        });
    },
    rename(renameItem) {
      this.renameModalVisible = true;
      this.renameForm = renameItem;
    },
    confirmRename() {
      this.$store
        .dispatch('dir/rename', this.renameForm)
        .then(res => {
          console.log('重命名成功', res);
          this.renameModalVisible = false;
        })
        .catch(reason => {
          console.log('重命名失败', reason);
        });
    },
    showCopyModal(copyItem, isCopy,isMulti) {
      this.isCopy = isCopy;
      this.isMultiple=isMulti;
      this.copyItem = copyItem;
      this.copyModalVisible = true;
      this.getDirTree();
    },
    confirmMoveAndCopy(isCopy, isMulti) {
      let url = '';
      if (isCopy) {
        url = 'dir/copy';
      } else {
        url = 'dir/move';
      }
      let sourceListId = [];
      if (isMulti) {
        console.log('多文件移动');
        sourceListId = this.selectedRows;
      } else {
        console.log('单文件文件移动');
        sourceListId.push(this.copyItem);
      }
      this.$store
        .dispatch(url, { targetId: this.targetKey, sourceListId: sourceListId })
        .then(res => {
          console.log('移动或复制成功', res);
          this.$message.success(res);
          this.copyModalVisible = false;
          this.getCurrentDirList(this.currentDirId);
        })
        .catch(reason => {
          console.log('复制或者移动失败', reason);
          this.$message.error(reason);
        });
    },
    onSelect(keys, event, selectedNodes) {
      console.log('选择中的目录', keys, event, selectedNodes);
      this.targetKey = keys[0];
    },
    downloadOneFile(downloadItem) {
      console.log('单个文件下载', downloadItem);
      this.$http
        .getBlob('tran/download/' + downloadItem.id)
        .then(result => {
          const url = window.URL.createObjectURL(new Blob([result]));
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          console.log(link);
          if (downloadItem.type === 'dir') {
            link.setAttribute('download', downloadItem.name + '.' + 'zip');
          } else {
            link.setAttribute('download', downloadItem.name + '.' + downloadItem.type);
          }
          console.log(link);
          document.body.appendChild(link);
          link.click();
          // 下载完成移除元素
          document.body.removeChild(link);
          // 释放掉blob对象
          window.URL.revokeObjectURL(url);
        })
        .catch(err => {
          console.log(err);
        });
      /*      this.$store
        .dispatch('file/downloadOneFile', downloadItem.id)
        .then(res => {
          console.log(res);
        })
        .catch(reason => {
          console.log(reason);
        });*/
    },
    mkdir() {
      this.mkdirModalVisible = true;
    },
    confirmMkdir() {
      this.mkdirForm.userId = this.$store.state.user.accountInfo.userId;
      this.mkdirForm.pid = this.currentDirId;
      this.$store
        .dispatch('dir/mkdir', this.mkdirForm)
        .then(res => {
          console.log(res);
          this.getCurrentDirList();
          this.mkdirModalVisible = false;
        })
        .catch(reason => {
          this.$message.error('操作失败:' + reason.data);
          console.log(reason);
        });
    },
    uploadFile() {
      console.log(this.$BUS);
      Bus.$emit('openUploader', {
        dirId: this.currentDirId,
        userId: this.$store.state.user.accountInfo.userId
      });
    },
    openRecyclingBin() {
      this.recycleBinVisible = true;
      this.$store
        .dispatch('dir/getRecycleBin', { userId: this.$store.state.user.accountInfo.userId })
        .then(res => {
          console.log('获取成功', res);
          this.recycleBinTable = res;
        })
        .catch(reason => {
          console.log('获取失败', reason);
        });
    },
    cleanRecyclingBin() {
      console.log("清空回收站");
      this.$store.dispatch('dir/cleanRecyclingBin',{userId:this.$store.state.user.accountInfo.userId})
      .then(res=>{
        console.log('清空回收站成功',res);
      }).catch(reason => {
        console.log('清空回收站失败',reason);
      })
    },
    restoreFile(item) {
      console.log('被恢复文件', item);
      this.$store
        .dispatch('dir/recovery', { fileId: item.id })
        .then(res => {
          console.log('恢复成功', res);
          this.$store
            .dispatch('dir/getRecycleBin', { userId: this.$store.state.user.accountInfo.userId })
            .then(res => {
              console.log('获取成功', res);
              this.recycleBinTable = res;
            })
            .catch(reason => {
              console.log('获取失败', reason);
            });
        })
        .catch(reason => {
          console.log('恢复失败', reason);
        });
    },
    removeCompletely(item) {
      console.log('彻底删除文件',item);
      this.$store
        .dispatch('dir/removeCompletely', { fileId: item.id })
        .then(res => {
          console.log('删除成功', res);
          this.$store
            .dispatch('dir/getRecycleBin', { userId: this.$store.state.user.accountInfo.userId })
            .then(res => {
              console.log('获取成功', res);
              this.recycleBinTable = res;
            })
            .catch(reason => {
              console.log('获取失败', reason);
            });
        })
        .catch(reason => {
          console.log('删除失败', reason);
        });
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      console.log('selectedRow changed: ', selectedRow);
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRow;
    },
    multiDown() {
      console.log('多文件下载', this.selectedRowKeys);
      console.log('多文件下载', this.selectedRows);
      this.$http
        .postBlob('/tran/multiDownload', this.selectedRows)
        .then(result => {
          const url = window.URL.createObjectURL(new Blob([result]));
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', this.currentDirName + '.' + 'zip');
          console.log(link);
          document.body.appendChild(link);
          link.click();
          // 下载完成移除元素
          document.body.removeChild(link);
          // 释放掉blob对象
          window.URL.revokeObjectURL(url);
        })
        .catch(reason => {
          console.log('下载失败', reason);
        });
      /*      this.$store
        .dispatch('file/downloadMultiFile', this.selectedRows)
        .then(res => {
          console.log('下载成功', res);
        })
        .catch(reason => {
          console.log('下载失败', reason);
        });*/
    },
    preview(fileId,fileType){
      console.log("点击了预览按钮");
      var url = 'http://127.0.0.1:8000/review/'+fileId+'.'+fileType; //要预览文件的访问地址
      window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
    }
  }
};
</script>

<style scoped>
.index-container {
  padding: 24px;
  background: #f0f2f5;
}
.file-size {
  font-size: 24px;
}
</style>
